import {Component} from '@angular/core';
import {IonicPage, LoadingController, NavController, NavParams, Platform, ToastController} from 'ionic-angular';
import {Keyboard} from "@ionic-native/keyboard";

import {Md5} from "ts-md5";
import {WebcastFavoriteListProvider} from "../../../providers/webcast/webcast-favorite-list/webcast-favorite-list";
import {WebcastDetailProvider} from "../../../providers/webcast/webcast-detail/webcast-detail";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {WebcastInfo} from "../../../model/pages/webcast/webcast-info";
import * as moment from "moment";
import {WebcastCommentItem} from "../../../model/pages/webcast/webcast-comment-item";
import {WechatService} from "../../../services/native/wechat/wechat.service";
import {ThemeBrowserService} from "../../../services/native/theme-browser/theme-browser.service";
import {UaTypeService} from "../../../services/utils/ua-type.service";

declare let VHALL_SDK;
declare let Wechat;
declare let $;

@IonicPage()
@Component({
    selector: 'page-webcast-detail',
    templateUrl: 'webcast-detail.html',
    providers: [
        WechatService,
        ThemeBrowserService
    ]
})

export class WebcastDetailPage {

    pageSubStyle;
    commentListWrapperStyle;
    pageContainerSubStyle;
    //收藏状态（接口返回）
    isFavorited: boolean = false;
    /**
     * 推送进进的直播ID
     */
    id: string;
    castId: string;
    castTitle: string;
    //直播详细信息
    castInfo: WebcastInfo;
    commentText: string;

    unix;
    tabs = {
        information: {
            title: '资料',
            isCurrent: false
        }, command: {
            title: '评论',
            isCurrent: false
        }, introduce: {
            title: '介绍',
            isCurrent: true
        }
    };
    toolItems = [];
    commentItemes: WebcastCommentItem[] = [];
    inputWebcastTextComment;
    inputingComment = false;
    showShareMenu: boolean;
    isLeaveWebcast = true;
    isKeyboardOpen = false;

    constructor(public navCtrl: NavController,
                private platform: Platform,
                public toastCtrl: ToastController,
                public webcastDetailProvider: WebcastDetailProvider,
                public webcastFavoriteListProvider: WebcastFavoriteListProvider,
                public keyboard: Keyboard,
                public wechatService: WechatService,
                public loadingCtrl: LoadingController,
                public themeBrowserService: ThemeBrowserService,
                public navParams: NavParams) {

        this.castInfo = {
            account: "v25487144",
            roomId: 178946447,
            // secretkey = '347dde5772443dcde5a1027b5f22283b';
            // secretkey = '143b23a5f1480cf9f33d661bc552ce83';   //api 使用
            // secretkey = 'e2ad432323a2b624b3ee6299a149e5ff';      //sdk 使用
            secretkey: "e2ad432323a2b624b3ee6299a149e5ff",

            userId: "8a7481d0620003d601620005d5330000",
            email: "userId@msl.com",
            appKey: "011668c7c13d706d8e6a1ef7a63ebd5f",
            host: "中宏保险",
            introduction: "中宏保险",
            isChat: 0,
            isFavorite: true,
            layout: 1,
            password: "11111111",
            username: "中宏保险",
            webcastImgUrl: "http://cnstatic01.e.vhall.com/upload/webinars/img_url/c0/a5/c0a54d322d5c69fd28902426a6c07525.png",
            webcastStartTime: 1522997058,
            webcastStartTimeStr: '',
            subject:''
        };

        this.toolItems = [
            this.tabs.introduce,
            this.tabs.command,
            this.tabs.information
        ];
        this.id = this.navParams.get('id');
        if (this.id) {
            this.castId = this.id;
            this.webcastDetailProvider.getCastDetailByCastId(this.id).subscribe(res => {
                this.castTitle = res['subject'];
                this.castInfo.roomId = res['roomId'];
            });
        }else {
            this.castId = this.navParams.get('castId');
            this.castTitle = this.navParams.get('castTitle');
            let roomId = this.navParams.get('roomId');
            if (roomId) this.castInfo.roomId = roomId;
        }
        // this.castId = this.navParams.get('castId');
        // this.castTitle = this.navParams.get('castTitle');
        // let roomId = this.navParams.get('roomId');
        // if (roomId) this.castInfo.roomId = roomId;

    }


    toolChanged(item) {
        this.toolItems.forEach(i => i.isCurrent = false);
        item.isCurrent = true;
    }

    ionViewDidLoad() {
        this.scriptInit();
        this.getCastDetailInfo();
        this.layout();
    }

    //sdk 脚本初始化
    scriptInit() {
        let userName = window.localStorage.getItem('userName');
        if (userName) {
            this.castInfo.username = userName;
        }

        // let $body = $('body');
        // window['$'] = $;
        // window['jQuery'] = $;
        // let vhalSdkScript = $("#vhalSdkScript");
        // if (!vhalSdkScript.length) {
        //
        //     let scriptUrl = './assets/webcast/jquery.mCustomScrollbar.concat.min.js';
        //     let scriptElement = $(`<script></script>`);
        //     scriptElement.attr('src', scriptUrl);
        //     $body.append(scriptElement);
        //
        //     scriptUrl = './assets/webcast/vhallSDK.js';
        //     scriptElement = $(`<script id="vhalSdkScript"></script>`);
        //     scriptElement.attr('src', scriptUrl);
        //     $body.append(scriptElement);
        //
        //     scriptUrl = './assets/webcast/underscore-min.js';
        //     scriptElement = $(`<script></script>`);
        //     scriptElement.attr('src', scriptUrl);
        //     $body.append(scriptElement);
        // }

    }
    getUserName(){
        return window.localStorage.getItem('userName');
    }

    //region 初始化直播播放器

    collected(){
        console.log(this.castInfo.roomId);
        this.webcastFavoriteListProvider.optFavorite(this.castInfo.roomId, 1).subscribe(res => {
            this.isFavorited = true;
            this.themeBrowserService.setStatus(this.isFavorited)
            this.showToast('收藏成功！');
            MessageBushService.setMessage(MessageBushService.keys.webCastFavoriteUpdated, '1');
        }, error2 => {
            console.log(error2,'error2');
            let msg = "收藏失败，请联系管理员！";
            if(error2.exception)msg = error2.exception;
            this.showToast(msg);
        });
    }

    unCollected(){
        this.webcastFavoriteListProvider.optFavorite(this.castInfo.roomId, 0).subscribe(res => {
            this.isFavorited = false;
            this.themeBrowserService.setStatus(this.isFavorited)
            this.showToast('取消收藏成功！');
            MessageBushService.setMessage(MessageBushService.keys.webCastFavoriteUpdated, '1');
        }, error2 => {
            console.log(error2,'error2');
            this.showToast('取消收藏失败，请联系管理员！');
        });
    }

    shareWaySelected(data){
        console.log(data,'shareWaySelected')
        if(data == 0){
            this.shareOut(0);
        }else{
            this.shareOut(1);
        }
    }
    //初始化直播播放器
    castInit() {

        if (!this.castInfo || !this.castInfo.roomId) {
            // this.toastCtrl.create({
            //     message: '获取房间id失败！',
            //     position: 'middle',
            //     duration: 1200
            // }).present();
            // console.log('获取房间id失败！');
            this.showToast('获取房间id失败！');
            return;
        }

        let sign = this.createSign();

        const webCasetUrl = `http://e.vhall.com/webinar/inituser/${
                this.castInfo.roomId
            }?email=${
                this.castInfo.email
            }&name=${this.castInfo.username}&k=${this.unix}`;

        let webcastContainer: HTMLIFrameElement = document.querySelector('.webcast-container') as HTMLIFrameElement;
        webcastContainer.src = webCasetUrl;

        // this.themeBrowserService.openBrowser(webCasetUrl,{
        //     status:this.isFavorited,
        //     id:this.castInfo.roomId,
        //     callback1:id => this.collected(),
        //     callback2:id => this.unCollected()
        // },{
        //     shareWaySelectedEvent:'shareWaySelectedEvent',
        //     buttons:[],
        //     shareCallback:data => this.shareWaySelected(data)
        // });

        // VHALL_SDK.init({
        //     account: this.castInfo.account,//必填，唯一用户id，与使用第三方创建用户接口所传的third_user_id需一致）
        //     email: this.castInfo.email,//参数必填，当前版本已不建议使用，为空即可
        //     username: this.castInfo.username,//必填，用户昵称用以在各模块中显示
        //     roomid: this.castInfo.roomId,//必填，当前聊天所在活动id
        //     app_key: this.castInfo.appKey,//必填，启用服务唯一验证，API/SDK权限申请后生成,此参数名在1.0.0版本中为appkey，使用当前版本时请更新
        //     signedat: this.unix,//必填，启用服务唯一验证，unix时间戳
        //     sign: sign,//必填，启用服务唯一验证，有效期一小时，见下面的生成规则
        //     facedom: '',//可选，当使用微吼表情时必填，呼出表情弹窗dom属性 如（'#id','.class'等）
        //     textdom: '.input-webcast-text-comment',//可选，当使用微吼表情时必填，插入表情文本dom属性 如（'#id','.class'等）
        //     videoContent: '.webcast-container',//【新】可选，当需要使用视频模块时，插入视频dom属性 如（'#id','.class'等）
        //     docContent: '.file-demo',//【新】可选，当需要使用文档模块时，插入视频dom属性 如（'#id','.class'等）
        // });
        //
        // //自动播放
        // VHALL_SDK.on("ready", function () {
        //     setTimeout(() => {
        //         let vhallH5Player = document.querySelector('#vhall-h5-player') as HTMLVideoElement;
        //         if (vhallH5Player)
        //             vhallH5Player.autoplay = true;
        //     }, 500);
        // });
        //
        // VHALL_SDK.on("chatMsg", function (t) {
        //     console.log(t, 'chatMsg');
        //     // alert(t);
        // });
        //
        // VHALL_SDK.on("questionMsg", function (t) {
        //     console.log("问答", t);
        //     // alert(t);
        // });
        //
        // VHALL_SDK.on("vhall_live_history_chat_msg", t => {
        //     if (t.code === 200) {
        //         if (t.data && t.data.length) {
        //
        //             this.prevFirstChat.equal =
        //                 this.prevFirstChat.user_name === t.data[0].user_name &&
        //                 this.prevFirstChat.content === t.data[0].content &&
        //                 this.prevFirstChat.time === t.data[0].time;
        //
        //             if (this.updateComment || !this.prevFirstChat.equal) {
        //                 this.commentItemes = t.data;
        //                 this.updateComment = false;
        //             }
        //
        //             this.prevFirstChat = {
        //                 user_name: t.data[0].user_name,
        //                 content: t.data[0].content,
        //                 time: t.data[0].time,
        //                 equal: false
        //             };
        //
        //         }
        //     }
        // });
        //
        // this.realtimeGetChatHistory();
    }



    //实时获取聊天记录
    realtimeGetChatHistory() {
        // let getChatHistory = () => {
        //     const self = this;
        //     VHALL_SDK.vhall_get_live_history_chat_msg();
        //     this.chatHistoryTimeout = setTimeout(() => {
        //         getChatHistory.apply(self);
        //     }, 3000);
        // };
        // getChatHistory.apply(this);
    }

    //创建签名
    createSign() {
        //时间戳
        this.unix = String(Math.round(new Date().getTime() / 1000));
        // this.unix = new Date().getTime();
        let $params = {
            "account": this.castInfo.account,
            "app_key": this.castInfo.appKey,
            "email": this.castInfo.email,
            "roomid": this.castInfo.roomId,
            "signedat": this.unix,
            "username": this.castInfo.username
        };
        let $value = "";
        for (let key in $params) {
            $value += key + $params[key];
        }

        let $value1 = this.castInfo.secretkey + $value + this.castInfo.secretkey;
        return Md5.hashStr($value1);

    }

    //endregion

    //评论
    inputLikeClick() {
        this.calculateCommentIputingHeight();

        this.inputingComment = true;
        setTimeout(() => {
            $('input.input-webcast-text-comment').focus();
        }, 500);
    }

    //评论直播
    comment(e) {
        if ('Enter' === e.key || 13 === e.keyCode) {

            if (this.commentText && this.commentText.trim()) {
                VHALL_SDK.sendChat({text: this.commentText.trim()});

                let now = new Date();
                let chatItem = new WebcastCommentItem();
                chatItem.user_name = this.castInfo.username;
                chatItem.time = `今天 ${now.getHours()}:${now.getMinutes()}`;
                chatItem.content = this.commentText;
                this.commentItemes.unshift(chatItem);

                this.commentText = '';
                if (this.inputWebcastTextComment && this.inputWebcastTextComment.length) {
                    this.inputWebcastTextComment.blur();
                }
            }

        }
    }

    layout() {


        let $container = $('.webcast-container');

        let prevHeight = 0;
        this.keyboard.onKeyboardShow().subscribe(e => {
            this.isKeyboardOpen = true;
            if (this.platform.is('ios') && this.isLeaveWebcast) {
                setTimeout(() => {
                    if(UaTypeService.isIphoneX){
                        $container.height(391);
                    }else if(UaTypeService.isIphone7P){
                        $container.height(345);
                    }else if(UaTypeService.isIphone7){
                        $container.height(340);
                    }else if(UaTypeService.isIphone5){
                        $container.height(246);
                    }else{
                        let $containerHeight = $container.height();
                        let tHeight = $containerHeight - e.keyboardHeight - this.vw(10);
                        if(tHeight >= prevHeight)prevHeight = tHeight;
                        $container.height(prevHeight);
                    }
                    // $container.height(screen.height - e.keyboardHeight - 70);
                },400);



            }
        });
        this.keyboard.onKeyboardHide().subscribe(e => {
            this.isKeyboardOpen = false;
            if (this.platform.is('ios') && this.isLeaveWebcast) {
                $container.css('height','100%');
            }
        });

        this.pageSubStyle = {};
        this.pageContainerSubStyle = {};
        this.commentListWrapperStyle = {};
        let wHeight = window.innerHeight;
        let pageEle = $('page-webcast-detail');
        let headHeight = pageEle.find('ion-header').height();
        let webcastHeight = pageEle.find('.webcast-container').height();
        let inputWrapperHeight = pageEle.find('.input-wrapper').height();
        let toolHeight = pageEle.find('.tool').height();

        this.inputWebcastTextComment = pageEle.find('.input-webcast-text-comment');
        let totalHeight = headHeight + webcastHeight + inputWrapperHeight + toolHeight;
        this.pageSubStyle.height = (wHeight - totalHeight) + 'px';
        this.pageContainerSubStyle.height = (this.vw(12.96) + (wHeight - totalHeight)) + 'px';
    }

    calculateCommentIputingHeight() {
        let pageEle = $('page-webcast-detail');
        let headHeight = pageEle.find('ion-header').height();
        let inputWrapperHeight1 = pageEle.find('.inputing-container').height();
        this.commentListWrapperStyle.maxHeight = (window.innerHeight - headHeight - inputWrapperHeight1) + 'px';
    }

    vw(v: number) {
        return window.innerWidth * v / 100;
    }


    //获取直播详情
    getCastDetailInfo(cb = null) {

        let self = this;
        this.webcastDetailProvider.getCastDetailByCastId(this.castId).subscribe(res => {
            this.castInfo = res as WebcastInfo;
            if (this.castInfo) {
                this.isFavorited = this.castInfo.isFavorite;
                if (this.castInfo.webcastStartTime) {
                    this.castInfo.webcastStartTimeStr = moment(this.castInfo.webcastStartTime * 1000).format('YYYY/MM/DD');
                }
                this.castInfo.email = `${this.getUserName()}@msl.com`;
                setTimeout(() => {
                    this.castInit.apply(self);
                }, 200);
            }
            if (cb) cb();
        });

    }

    favoriteClicked() {
        if (this.isFavorited) {
            this.webcastFavoriteListProvider.optFavorite(this.castInfo.roomId, 0).subscribe(res => {
                this.isFavorited = !this.isFavorited;
                this.showToast('取消收藏成功！');
                MessageBushService.setMessage(MessageBushService.keys.webCastFavoriteUpdated, '1');
            }, error2 => {
                this.showToast('取消收藏失败，请联系管理员！');
            });
        } else {
            this.webcastFavoriteListProvider.optFavorite(this.castInfo.roomId, 1).subscribe(res => {
                this.isFavorited = !this.isFavorited;
                this.showToast('收藏成功！');
                MessageBushService.setMessage(MessageBushService.keys.webCastFavoriteUpdated, '1');
            }, error2 => {
                let msg = "收藏失败，请联系管理员！";
                if(error2.exception)msg = error2.exception;
                this.showToast(msg);
            });
        }
    }

    backHandle() {
        if (this.inputingComment) {
            this.inputingComment = false;
            return;
        }
        this.navCtrl.pop();
    }

    /**
     *  安卓返回键
     */
    backToProPage() {
        if (this.inputingComment) {
            this.inputingComment = false;
            return;
        }
        this.navCtrl.pop(null);
    }

    // 安卓返回键
    private backButtonHandle = () => this.backToProPage();

    inputingRuturnClick() {
        this.inputingComment = false;
    }

    showToast(msg: string) {
        this.toastCtrl.create({
            message: msg,
            position: 'middle',
            duration: 1200
        }).present();
    }

    delHtmlTag(str){
        let result = str.replace(/&nbsp;/ig, "");
        return result.replace(/<[^>]+>/g,"");//去掉所有的html标记
    }

    shareOut(scene) {

        let loading = this.loadingCtrl.create({
            spinner: 'circles',
            content: '正在打开微信',
            dismissOnPageChange: false,
            enableBackdropDismiss: true
        });
        loading.present();

        this.webcastDetailProvider.getShareLink(this.castInfo.roomId).subscribe(result => {
            let shareLink = result;
            this.castInfo.webcastImgUrl = 'http://img.mp.itc.cn/upload/20160909/29ebda5a513c409881d6a586faa698c8_th.jpg';
            let intrductionPure = this.delHtmlTag(this.castInfo.introduction?this.castInfo.introduction:this.castInfo.subject);
            let shortName = this.delHtmlTag(this.castInfo.introduction?this.castInfo.introduction:this.castInfo.subject);
            let limit = 12;
            shortName = shortName.length < limit ? shortName : shortName.slice(0,limit);
            //分享给朋友0,分享到朋友圈1
            this.wechatService.share(scene, 'send-link-thumb-remote', {
                    link:shareLink,
                    thumb: this.castInfo.webcastImgUrl,
                    shortName,
                    description: intrductionPure
                }, () => {
                    loading.dismiss();
                }
                , reason => {
                    //this.showToast(`分享失败:${reason}`);
                    if(reason!='用户点击取消并返回'){
                        this.showToast(`分享失败:${reason}`);
                    }
                    loading.dismiss();
                }
            );
            setTimeout(() => {
                loading.dismiss();
            },10000);

            // this.wechatService.isInstalled().subscribe(res => {
            //     if(res.flag){
            //
            //     }else{
            //         loading.dismiss();
            //         this.showToast(`请安装微信：${res.reason}`);
            //     }
            // });


        });


    }

    ionViewWillLeave() {
        this.isLeaveWebcast = false;
        this.showShareMenu = false;

        if(this.isKeyboardOpen){
            let $inputFocus = $("#inputFocus").focus();
            setTimeout(() => {
                $inputFocus.blur();
            },100);
        }

    }
}
